﻿(function ($) {
    var methods = {
        init: function (options) {
            var defaultSettings = {
                debug: false,
                baseUrl: '',
                method: '',
                paginationContainer: null,
                pageIndex: null,
                pageSize: null,
                pagingStyle: pagingStyleEnum.none,
                parameters: {},
                implictFirstGet: false,
                isCrossDomain: true,
                onDataReady: null,
                onError: null
            };
            var $this = $(this);
            if (options) {
                $.extend(defaultSettings, options);
            };

            var data = $this.data('pagedList'),
					pagedList = $(this, {
					    options: defaultSettings
					});

            // If the plugin hasn't been initialized yet
            if (!data) {
                //options
                var o = defaultSettings;

                var idChain = $this[0].id;

                $(this).data('pagedList', {
                    target: $this,
                    pagedList: pagedList,
                    options: o
                });

                data = $this.data('pagedList');
            }
            else {
                data.options = defaultSettings;
            }
            jQuery.support.cors = true;
            if (data.options.implictFirstGet == true) {
                $(this).pagedList('ajaxCall', data.options.pageIndex, data.options.pageSize);
            }
            if (data.options.debug == true) {
                //alert(browser + ' (runtimes: ' + uploadRuntimes + ')');
            }
            return $this;
        },
        destroy: function () {
            return this.each(function () {
                var $this = $(this),
					data = $this.data('pagedList');

                // Namespacing FTW
                $this.unbind('.pagedList');
                data.pagedList.remove();
                $this.removeData('pagedList');
            })
        },
        ajaxCall: function (pageIndex, pageSize) {
            var $this = $(this),
				data = $this.data('pagedList');
            var pIndex = data.options.pageIndex;
            var pSize = data.options.pageSize;

            if (pageIndex) {
                pIndex = pageIndex;
            }
            if (pageSize) {
                pSize = pageSize;
            }
            var restUrl = data.options.isCrossDomain ? data.options.baseUrl + '?method=' + data.options.method + '&' : data.options.baseUrl + data.options.method + '?';
            $.each(data.options.parameters, function (key, value) {
                restUrl = restUrl + (restUrl.endsWith('?') ? '' : '&') + key + '=' + value;
            });
            if (pIndex != null) {
                restUrl = restUrl + (restUrl.endsWith('?') ? '' : '&') + 'page=' + pIndex;
            }
            if (pSize != null) {
                restUrl = restUrl + (restUrl.endsWith('?') ? '' : '&') + 'size=' + pSize;
            }

            $this.block({
                message: '<span>Processing</span>',
                css: { border: '1px solid silver' }
            });
            $.ajax({
                url: restUrl,
                global: false,
                type: "GET",
                dataType: "json",
                processdata: false,
                async: true,
                success: function (jsonData, textStatus, jqXHR) {
                    if (!jsonData || !jsonData.Code || jsonData.Code == 0) {
                        if (typeof (data.options.onDataReady) == 'function') {
                            data.options.onDataReady.apply(data.target, [jsonData, pIndex, pSize]);
                        }
                        methods.onDataReady.apply(data.target, [jsonData, pIndex, pSize]);
                    }
                    else {
                        if (typeof (data.options.onError) == 'function') {
                            data.options.onError.apply(data.target, [jsonData.Code, jsonData.Message]);
                        }
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (typeof (data.options.onError) == 'function') {
                        data.options.onError.apply(data.target, [null, errorThrown]);
                    }
                },
                complete: function (jqXHR, textStatus) {
                    $(data.target).unblock();
                }
            });
        },
        onDataReady: function (jsonData, pageIndex, pageSize) {
            if (!jsonData) {
                return;
            }
            methods.createPagination.apply($(this), [pageIndex, pageSize, jsonData.TotalRecords]);
        },
        createPagination: function (pageIndex, pageSize, totalRecords) {
            var $this = $(this),
				data = $this.data('pagedList');

            if (!data.options.paginationContainer) {
                return;
            }
            var pIndex = data.options.pageIndex;
            var pSize = data.options.pageSize;
            var pStyle = data.options.pagingStyle;
            var totalPages = 1;
            if (pageSize != 0 && pageSize != 2147483647) {
                totalPages = Math.ceil(totalRecords / pageSize);
                if (totalPages == 0) {
                    totalPages = 1;
                }
            }
            if (pageIndex) {
                pIndex = pageIndex;
            }
            if (pageIndex) {
                pIndex = pageIndex;
            }

            var pagingHtml = '';
            $(data.options.paginationContainer).empty();
            switch (pStyle) {
                case pagingStyleEnum.simple:
                    var prev = $($(this).pagedList('createPageLink', pIndex, totalPages, pagingLinkTypeEnum.prev));
                    var next = $($(this).pagedList('createPageLink', pIndex, totalPages, pagingLinkTypeEnum.next));
                    $(data.options.paginationContainer).append(prev);
                    pagingHtml = (pageIndex + 1) + " of " + totalPages;
                    $(data.options.paginationContainer).append(pagingHtml);
                    $(data.options.paginationContainer).append(next);
                    break;
                default:
                    break;
            }
        },
        createPageLink: function (pageIndex, totalPages, linkType) {
            var $this = $(this),
				data = $this.data('pagedList');

            var pIndex = data.options.pageIndex;
            var pSize = data.options.pageSize;

            if (pageIndex) {
                pIndex = pageIndex;
            }

            var pagingCtrl = null;
            var cssClass = linkType == pagingLinkTypeEnum.next ? 'next' : (linkType == pagingLinkTypeEnum.prev ? 'prev' : '');
            var parentId = $this.attr('id');
            switch (linkType) {
                case pagingLinkTypeEnum.prev:
                    if (totalPages > 1 && pageIndex > 0) {
                        //pagingCtrl = $("<a id='" + parentId + "_prev' href='#" + parentId + "' class='" + cssClass + "'></a>");
                        pagingCtrl = $("<a id='" + parentId + "_prev' href='javascript: void(0)' class='" + cssClass + "'></a>");
                        pagingCtrl.bind('click.pagedList', function () {
                            methods.ajaxCall.apply(data.target, [pIndex - 1, pSize]);
                        });
                    }
                    else {
                        //pagingCtrl = $("<a id='" + parentId + "_prev' href='#" + parentId + "' class='" + cssClass + " inactive'></a>");
                        pagingCtrl = $("<a id='" + parentId + "_prev' href='javascript: void(0)' class='" + cssClass + " inactive'></a>");
                    }
                    break;
                case pagingLinkTypeEnum.next:
                    if (pageIndex + 1 < totalPages) {
                        //pagingCtrl = $("<a id='" + parentId + "_next' href='#" + parentId + "' class='" + cssClass + "'></a>");
                        pagingCtrl = $("<a id='" + parentId + "_next' href='javascript: void(0)' class='" + cssClass + "'></a>");
                        pagingCtrl.bind('click.pagedList', function () {
                            methods.ajaxCall.apply(data.target, [pIndex + 1, pSize]);
                        });
                    }
                    else {
                        //pagingCtrl = $("<a id='" + parentId + "_next' href='#" + parentId + "' class='" + cssClass + " inactive'></a>");
                        pagingCtrl = $("<a id='" + parentId + "_next' href='javascript: void(0)' class='" + cssClass + " inactive'></a>");
                    }
                    break;
                default:
                    break;
            }
            return pagingCtrl;
        },

        onError: function (errorCode, errorMessage) {
            alert(errorThrown);
        }
    };

    $.fn.pagedList = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does nost exist on jQuery.pagedList');
        }
    };
})(jQuery);

var pagingStyleEnum = { none: 0, simple: 1, complex: 2 };
var pagingLinkTypeEnum = { none: 0, prev: 1, next: 2 };
